package com.jarasoft.AMP3MP;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.MediaStore;

public class AndroidMP3MusicPlayerService extends Service {

	public static final int NOTIFICATION_ID = 1543; // Unique ID
	int pos = 0;
	static final int MSG_CONTROL = 0;
	private List<List<String>> songs;
	private MediaPlayer player = new MediaPlayer();
	private NotificationManager notifManager;
	private Thread thr;
	private Service main_service;

	public static final String PLAYPAUSEACTION = "com.jarasoft.AMP3MP.PLAYPAUSE";
	public static final String STOPACTION = "com.jarasoft.AMP3MP.STOP";
	public static final String PREVACTION = "com.jarasoft.AMP3MP.PREV";
	public static final String NEXTACTION = "com.jarasoft.AMP3MP.NEXT";
	public static final String PLAYBACTION = "com.jarasoft.AMP3MP.PLAYB";
	public static final String PAUSEBACTION = "com.jarasoft.AMP3MP.PAUSEB";
	public static final String PROGRESSACTION = "com.jarasoft.AMP3MP.PROGRESS";
	public static final String SONGINFOACTION = "com.jarasoft.AMP3MP.SONGINFO";
	public static final String ARTISTACTION = "com.jarasoft.AMP3MP.ARTISTACTION";
	public static final String DISCACTION = "com.jarasoft.AMP3MP.DISCACTION";
	public static final String FOLACTION = "com.jarasoft.AMP3MP.FOLACTION";
	private BroadcastReceiver playpausereceiver, stopreceiver, prevreceiver, nextreceiver, artireceiver, discreceiver,
	      folreceiver;

	private static boolean isRunning = false;
	private static boolean pause = true;

	@Override
	public void onCreate() {
		main_service = this;
		thr = new Thread(null, work, "AMP3PService");

	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		// updateSongList();
		songs = new ArrayList<List<String>>();
		songsby(intent.getExtras().getString("CURLIST"));
		if (intent.getExtras().containsKey("POS")) {
			pos = intent.getExtras().getInt("POS");
		} else {
			pos = 0;
		}
		thr.start();
		isRunning = true;
		startbroad();

		notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(android.R.drawable.btn_radio, "Android MP3 Music Player", System
		      .currentTimeMillis());
		/* 3. Define the Notification's expanded message and Intent */
		String title = "Android MP3 Music Player";
		String message = "Click this panel to go to the GUI.";
		Intent intent2 = new Intent(main_service, AndroidMP3MusicPlayerActivity.class);
		PendingIntent notifIntent = PendingIntent.getActivity(main_service, 0, intent2, 0);
		notification.setLatestEventInfo(main_service, title, message, notifIntent);
		/* 4. Pass the Notification to the NotificationManager */
		notifManager.notify(NOTIFICATION_ID, notification);

		return Service.START_STICKY;
	}

	@Override
	public void onDestroy() {
		((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID);
		stopbroad();
		isRunning = false;
		pause = false;
		main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PLAYBACTION));
		Intent i = new Intent(AndroidMP3MusicPlayerService.PROGRESSACTION);
		i.putExtra("MAXPB", 1);
		i.putExtra("PROPB", 0);
		main_service.sendBroadcast(i);
		i = new Intent(AndroidMP3MusicPlayerService.SONGINFOACTION);
		i.putExtra("SONGINFO", "");
		i.putExtra("POS", -1);
		main_service.sendBroadcast(i);
		player.stop();
		thr.stop();
	}

	/**
	 * The function that runs in our worker thread
	 */
	Runnable work = new Runnable() {
		public void run() {
			while ((isRunning) && (pos < songs.size())) {
				if (player != null) {player.reset();}
				
				File song = new File(songs.get(pos).get(1));
				Uri suri = Uri.fromFile(song);
				player = MediaPlayer.create(AndroidMP3MusicPlayerService.this, suri);
				if (player != null) {
					System.out.println("AQUI LLEGUE1");
					player.start();
					main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PAUSEBACTION));
					pause = false;
					Intent i;
					while ((player.isPlaying() || pause) && (isRunning)) {
						i = new Intent(AndroidMP3MusicPlayerService.PROGRESSACTION);
						i.putExtra("MAXPB", player.getDuration());
						i.putExtra("PROPB", player.getCurrentPosition());
						main_service.sendBroadcast(i);
						i = new Intent(AndroidMP3MusicPlayerService.SONGINFOACTION);
						i.putExtra("SONGINFO", song.getName());
						i.putExtra("POS", pos);
						main_service.sendBroadcast(i);
						SystemClock.sleep(100);
					}
				}
				SystemClock.sleep(100);
				pos++;
			}

			AndroidMP3MusicPlayerService.this.stopSelf();
		}
	};

	public static boolean isRunning() {
		return isRunning;
	}

	public static boolean isPause() {
		return pause;
	}

	private void startbroad() {
		IntentFilter theFilter = new IntentFilter();
		theFilter.addAction(PLAYPAUSEACTION);
		playpausereceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				if (pause) {
					main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PAUSEBACTION));
					if (intent.hasExtra("POS")) {
						pos = intent.getExtras().getInt("POS") - 1;
						player.stop();
					} else {
						player.start();
					}
					pause = false;
				} else {
					if (intent.hasExtra("POS")) {
						pos = intent.getExtras().getInt("POS") - 1;
						player.stop();
						pause = false;
					} else {
						main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PLAYBACTION));
						player.pause();
						pause = true;
					}
				}
			}
		};
		registerReceiver(playpausereceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(STOPACTION);
		stopreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				player.stop();
				main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PLAYBACTION));
				isRunning = false;
			}
		};
		registerReceiver(stopreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(NEXTACTION);
		nextreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				player.stop();
				pos = (pos + 1 >= songs.size()) ? -1 : pos;
				main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PAUSEBACTION));
				pause = false;
			}
		};
		registerReceiver(nextreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(PREVACTION);
		prevreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				pos = (pos - 1 < 0) ? -1 : pos - 2;
				player.stop();
				main_service.sendBroadcast(new Intent(AndroidMP3MusicPlayerService.PAUSEBACTION));
				pause = false;
			}
		};
		registerReceiver(prevreceiver, theFilter);

		theFilter = new IntentFilter();

		theFilter.addAction(ARTISTACTION);
		artireceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				pos = -1;
				songs.clear();
				songsby(MediaStore.Audio.Media.ARTIST);
				player.stop();
				pause = false;
			}
		};
		registerReceiver(artireceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(DISCACTION);
		discreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				pos = -1;
				songs.clear();
				songsby(MediaStore.Audio.Media.ALBUM);
				player.stop();
				pause = false;
			}
		};
		registerReceiver(discreceiver, theFilter);

		theFilter = new IntentFilter();
		theFilter.addAction(FOLACTION);
		folreceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
				pos = -1;
				songs.clear();
				songsby(MediaStore.Audio.Media.DATA);
				player.stop();
				pause = false;
			}
		};
		registerReceiver(folreceiver, theFilter);
	}

	private void stopbroad() {
		unregisterReceiver(playpausereceiver);
		unregisterReceiver(stopreceiver);
		unregisterReceiver(nextreceiver);
		unregisterReceiver(prevreceiver);
		unregisterReceiver(artireceiver);
		unregisterReceiver(discreceiver);
		unregisterReceiver(folreceiver);
	}

	private void songsby(String orderby) {
		String[] projection = { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.TRACK,
		      MediaStore.Audio.Media.YEAR, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM_ID,
		      MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ALBUM_KEY, MediaStore.Audio.Media.TITLE,
		      MediaStore.Audio.Media.TITLE_KEY, MediaStore.Audio.Media.ARTIST_ID, MediaStore.Audio.Media.ARTIST };

		Cursor mCursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, projection, null, null,
		      orderby);

		songs.clear();
		String name;
		List<String> track;
		if (mCursor.moveToFirst()) {
			do {
				name = mCursor.getString(mCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
				if (name.endsWith(".mp3")) {
					track = new ArrayList<String>();
					track.add(0, mCursor.getString(mCursor.getColumnIndexOrThrow(orderby)));
					track.add(1, name);
					songs.add(track);
				}
			} while (mCursor.moveToNext());

		}

	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

}
